package com.changyinBus.web.controller.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.changyinBus.common.utils.IDGenerator;
import com.changyinBus.common.utils.uuid.UUID;
import com.changyinBus.web.controller.service.WeChatTransferService;
import com.changyinBus.web.controller.weChartPay.service.WeChatPaySignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import okhttp3.*;


import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service
public class WeChatTransferServiceImpl implements WeChatTransferService {
    private static final Logger log = LoggerFactory.getLogger(WeChatTransferServiceImpl.class);
    @Resource
    private WeChatPaySignature weChatPaySignature;
    /**
     * 应用ID（如小程序或公众号AppID）
     */
    @Value("${wechat.pay.appId}")
    private String appId;

    // 微信商家转账API地址
    private static final String TRANSFER_URL = "/v3/fund-app/mch-transfer/transfer-bills";
    private final OkHttpClient httpClient = new OkHttpClient();


    @Override
    public JSONObject transfer(String openid, int amount, String partnerTradeNo, String remark) throws Exception{
        // 1. 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.set("appid", appId);
        requestBody.set("out_bill_no", partnerTradeNo);        //商户单号
        requestBody.set("transfer_scene_id", "1000");
        requestBody.set("openid", openid);
        requestBody.set("transfer_amount", amount);
        requestBody.set("transfer_remark", remark);
        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        json.put("info_type","活动名称");
        json.put("info_content","新会员有礼");
        jsonArray.add(json);
        json = new JSONObject();
        json.put("info_type","奖励说明");
        json.put("info_content","注册会员抽奖一等奖");
        jsonArray.add(json);
        requestBody.set("transfer_scene_report_infos" , jsonArray);  //转账场景报备信息

        String body = JSONUtil.toJsonStr(requestBody);
        //log.info("微信转账请求体：{}", body);
        // 2. 构建Authorization请求头
        String authHeader  = weChatPaySignature.generateAuthHeader("POST", TRANSFER_URL, body);
        // 3. 发送HTTP请求
        Request request = new Request.Builder()
                .url("https://api.mch.weixin.qq.com" + TRANSFER_URL)
                .addHeader("Authorization", authHeader)
                .addHeader("Accept", "application/json")
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(body, MediaType.parse("application/json")))
                .build();
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("微信转账API调用失败，状态码：{}，响应体：{}", response.code(), response.body().string());
                throw new IOException("微信转账API调用失败: " + response.code());
            }
            String responseBody = response.body().string();
            //log.info("微信转账API响应：{}", responseBody);

            // 4. 解析响应，获取微信批次单号
            JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
            return jsonResponse;
        }
    }

    /**
     * 构建转账明细列表（单笔）
     */
    private List<Map<String, Object>> buildTransferDetail(String openid, BigDecimal amount, String remark) {
        Map<String, Object> detail = new HashMap<>();
        String detailNo = UUID.randomUUID().toString().replace("-", "").substring(0, 32); // 明细单号
        detail.put("out_detail_no", detailNo);
        detail.put("transfer_amount", amount.multiply(new BigDecimal("100")).intValue());
        detail.put("transfer_remark", remark);
        detail.put("openid", openid);
        // detail.put("user_name", "示例用户名");
        return Collections.singletonList(detail);
    }

}
